#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper;
use XMLRPC::Lite;
use Text::Iconv;

my $iconv = new Text::Iconv("utf-8", "utf-8");

sub _convert
{
	my $iconv = shift;
	my $data  = shift;

	if (ref $data eq 'ARRAY')
	{
		my @result;
		foreach my $element(@{$data})
		{
			push @result, _convert($iconv, $element);
		}
		return \@result;
	}
	elsif (ref $data eq 'HASH')
	{
		my %result;
		while (my ($key, $val) = each(%{$data}))
		{
			$result{$key} = _convert($iconv, $val);
		}
		return \%result;
	}
	else
	{
		return $iconv -> convert($data);
	}
return undef;
}


my $xmlrpc = new XMLRPC::Lite;
$xmlrpc -> proxy('http://localhost/rpc');
$xmlrpc -> transport -> default_header('X-Rambler-Inside' => '1');
$xmlrpc -> transport -> default_header('Host' => 'mail.rambler.ru');

my $response;

# Create token
$response = $xmlrpc -> call('XMLRPC::CSRF::create_token', { method => 'XMLRPC::CSRF::self_test' }) -> result;
print Dumper(_convert($iconv, $response));

my $token = $response -> {'token'} -> {'key'};
warn "token is `$token`";

# Check token
$response = $xmlrpc -> call('XMLRPC::CSRF::check_token', { method => 'XMLRPC::CSRF::self_test', token => $token }) -> result;
print Dumper(_convert($iconv, $response));

# Check token with invalid method
$response = $xmlrpc -> call('XMLRPC::CSRF::check_token', { method => 'XMLRPC::CSRF::no_such_method', token => $token }) -> result;
print Dumper(_convert($iconv, $response));

# Execute method, not ok
$response = $xmlrpc -> call('XMLRPC::CSRF::self_test', { }) -> result;
print Dumper(_convert($iconv, $response));

# Execute method, ok
$response = $xmlrpc -> call('XMLRPC::CSRF::self_test', { token => $token }) -> result;
print Dumper(_convert($iconv, $response));

# Execute method, not ok
$response = $xmlrpc -> call('XMLRPC::CSRF::self_test', { token => $token }) -> result;
print Dumper(_convert($iconv, $response));

# Check token
$response = $xmlrpc -> call('XMLRPC::CSRF::delete_token', { token => $token }) -> result;
print Dumper(_convert($iconv, $response));

